package handler;

import entity.AdminDO;
import service.AdminService;
import service.impl.AdminServiceImp;
import student.view.LoginView;
import student.view.MainView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class LoginHandler extends KeyAdapter implements ActionListener {
    private LoginView loginView;
    public LoginHandler(LoginView loginView){
        this.loginView=loginView;
    }
    public void login(){
        String user=loginView.getUserTxt().getText();
        char[] chars=loginView.getPwTxt().getPassword();
        if(user==null||"".equals(user.trim())||chars==null){
            JOptionPane.showMessageDialog(loginView,"请输入用户名密码");
            return;
        }
        String pwd=new String(chars);
        AdminService adminService=new AdminServiceImp();
        AdminDO adminDO=new AdminDO();
        adminDO.setUsername(user);
        adminDO.setPwd(pwd);
        boolean flag= adminService.validatAdmin(adminDO);
        if(flag){
            new MainView();
            loginView.dispose();
        }
        else{
            JOptionPane.showMessageDialog(loginView,"用户名密码错误");
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton=(JButton) e.getSource();
        String text=jButton.getText();
        if(text.equals("重置")){
            loginView.getUserTxt().setText("");
            loginView.getPwTxt().setText("");
        }
        else if(text.equals("登录")){
            login();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(KeyEvent.VK_ENTER==e.getKeyCode()){
            login();
        }
    }
}
